package com.jiehoo.ooqi;

/**
 * Query info builder, provide convenient methods to construct a QueryInfo.
 * 
 */
public class QueryBuilder {
	private QueryInfo queryInfo;

	public QueryBuilder() {
		queryInfo = new QueryInfo();
	}

	public QueryInfo getQueryInfo() {
		return queryInfo;
	}

	public void addSelect(String name) {
		queryInfo.getSelects().add(new Field(name));
	}

	public void addSelect(From from, String name) {
		queryInfo.getSelects().add(new Field(from, name));
	}

	public void addSelect(From from, String name, Function function) {
		queryInfo.getSelects().add(new Field(from, name, function));
	}

	public From addFrom(Class<?> target, String alias) {
		From from = new From(target, alias);
		queryInfo.getFroms().add(from);
		return from;
	}

	public From addFrom(String table, String alias) {
		From from = new From(table, alias);
		queryInfo.getFroms().add(from);
		return from;
	}

	/**
	 * Join model class to default model class
	 * 
	 * @param c
	 *            model class
	 * @param alias
	 *            model class alias
	 * @param from
	 *            field for default model class
	 * @param to
	 *            field for specified model class
	 * @return From for specified model class
	 */
	public From join(Class<?> c, String alias, String from, String to) {
		From f = new From(c, alias);
		queryInfo.getFroms().add(f);
		queryInfo.getConditions().add(
				new Condition(new Field(queryInfo.getDefaultFrom(), from),
						Operator.equal, new Field(f, to)));
		return f;
	}

	public void addGroupBy(String groupBy) {
		queryInfo.getGroupBys().add(new Field(groupBy));
	}
}
